package com.jzg.jcptadmin.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.StringUtils;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 选择时间界面
 *
 * @author 作者 彭坤
 * @version 创建时间：2016-5-4
 */
@SuppressLint("NewApi")
public class SelectDateActivity1 extends BaseActivity {


    int win_width;
    int win_height;
    @Bind(R.id.time_title)
    TextView timeTitle;
    @Bind(R.id.yearNumberPicker)
    NumberPicker yearNumberPicker;
    @Bind(R.id.monthNumberPicker)
    NumberPicker monthNumberPicker;
    @Bind(R.id.dial_layout)
    LinearLayout dialLayout;
    @Bind(R.id.dayNumberPicker)
    NumberPicker dayNumberPicker;

    private int currYear = StringUtils.getCurrent(StringUtils.TimeType.YEAR);//默认当前年
    private int currMonth = StringUtils.getCurrent(StringUtils.TimeType.MONTH);//默认当前月
    private int currDay = StringUtils.getCurrent(StringUtils.TimeType.DAY);//默认当前日
    private int opYear = StringUtils.getCurrent(StringUtils.TimeType.YEAR);//默认当前年
    private int opMonth = StringUtils.getCurrent(StringUtils.TimeType.MONTH);//默认当前月
    private int opDay = StringUtils.getCurrent(StringUtils.TimeType.DAY);//默认当前日


    private int maxYear = StringUtils.getCurrent(StringUtils.TimeType.YEAR);//默认当前年
    private int maxMonth = 12;
    private int minMonth = 1;
    private final int maxDay = 31;
    private final int minDay = 1;
    private int minYear;
    private boolean isEnd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setFinishOnTouchOutside(true);

        setContentView(R.layout.act_day_sheettime);
        ButterKnife.bind(this);
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高
        WindowManager.LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
        Point size = new Point();
        d.getSize(size);
        win_width = size.x;
        win_height = size.y;
        p.gravity = Gravity.BOTTOM;
        p.height = (int) (win_height * 0.5); // 高度设置为屏幕的0.6
        p.width = (int) (win_width * 1); // 宽度设置为屏幕的1
        p.alpha = 1.0f;// 设置透明度
        this.getWindow().setAttributes(p);


        Intent intent = getIntent();
        minYear = intent.getIntExtra("Minyear", 1990);
        minMonth = intent.getIntExtra("MinMonth", 1);
        maxYear = intent.getIntExtra("MaxYear", maxYear);
        maxMonth = intent.getIntExtra("maxMonth", maxMonth);
        opYear = intent.getIntExtra("opYear", maxYear);
        opMonth = intent.getIntExtra("opMonth", currMonth);
        opDay = intent.getIntExtra("opDay", currDay);
        isEnd = intent.getBooleanExtra("isEnd", false);
        String title = intent.getStringExtra(Constant.KEY_TITLE);
        if (!TextUtils.isEmpty(title)) {
            timeTitle.setText(title);
        }

        yearNumberPicker.setMaxValue(opYear);
        yearNumberPicker.setMinValue(minYear);
        yearNumberPicker.setValue(opYear);

        monthNumberPicker.setMaxValue(opMonth);
        if(minYear==maxYear){
            monthNumberPicker.setMinValue(minMonth);
        }else{
            monthNumberPicker.setMinValue(1);
        }


        monthNumberPicker.setValue(opMonth);

        dayNumberPicker.setMaxValue(currDay);
        dayNumberPicker.setMinValue(minDay);

        dayNumberPicker.setValue(opDay > currDay ? currDay : opDay);

        yearNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        monthNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        yearNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                int year = picker.getValue();
                currYear = year;
                updateMonth();
            }
        });
        monthNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                int month = picker.getValue();
                currMonth = month;
                updateMonth();

            }
        });
        dayNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                int day = picker.getValue();
                currDay = day;
            }
        });
        updateMonth();

    }


    public void updateMonth() {
        //当前年
        if (currYear == opYear) { //如果选择当前年，则重新设置月和日的范围，不等大于当前月，不能大于当前日
            monthNumberPicker.setMaxValue(opMonth);
            if(minYear==maxYear){
                monthNumberPicker.setMinValue(minMonth);
            }else{
                monthNumberPicker.setMinValue(1);
            }
        } else if (yearNumberPicker.getValue() == minYear) {
            monthNumberPicker.setMaxValue(maxMonth);
            monthNumberPicker.setMinValue(minMonth);
        } else {
            monthNumberPicker.setMaxValue(12);
//            monthNumberPicker.setValue(currMonth);
            monthNumberPicker.setMinValue(1);
        }
        updateDay();

    }

    public void updateDay() {
        int year = yearNumberPicker.getValue();
        int month = monthNumberPicker.getValue();
        if (is31(month)) {
            dayNumberPicker.setMaxValue(31);
            dayNumberPicker.setMinValue(1);
            dayNumberPicker.setValue(1);
        } else {
            if (month == 2) {
                if (isRunNian(String.valueOf(year))) {
                    dayNumberPicker.setMaxValue(29);
                    dayNumberPicker.setMinValue(1);
                    dayNumberPicker.setValue(1);
                } else {
                    dayNumberPicker.setMaxValue(28);
                    dayNumberPicker.setMinValue(1);
                    dayNumberPicker.setValue(1);
                }

            } else {
                dayNumberPicker.setMaxValue(30);
                dayNumberPicker.setMinValue(1);
                dayNumberPicker.setValue(1);
            }
        }
        if (year == opYear) {//如果选择当前年，则重新设置月和日的范围，不等大于当前月，不能大于当前日
            monthNumberPicker.setMaxValue(opMonth);

            if (month == opMonth) {
                if (isEnd) {
                    dayNumberPicker.setMaxValue(StringUtils.getCurrent(StringUtils.TimeType.DAY));
                    dayNumberPicker.setMinValue(1);
                    dayNumberPicker.setValue(1);
                } else {
                    dayNumberPicker.setMaxValue(opDay);
                    dayNumberPicker.setMinValue(1);
                    dayNumberPicker.setValue(opDay);
                }

            }
        }
        if (year == minYear) {//如果选择当前年，则重新设置月和日的范围，不等大于当前月，不能大于当前日
            if (month == minMonth) {
                dayNumberPicker.setMinValue(opDay);
            }

        }

    }

    /**
     * 根据月份判断是否是31天
     *
     * @param month
     * @return
     */
    public boolean is31(int month) {
        Pattern pattern = Pattern.compile("([13578]|1[02])");
        Matcher matcher = pattern.matcher(month + "");
        return matcher.matches();
    }

    /**
     * 判断是否是闰年
     *
     * @param year
     * @return
     */
    public boolean isRunNian(String year) {
        Pattern pattern = Pattern.compile("(([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))");
        Matcher matcher = pattern.matcher(year);
        return matcher.matches();
    }

    public void time_done(View view) {
        back_data();
        finish();
    }


    public void back_data() {
        Intent in = new Intent();
        int year = yearNumberPicker.getValue();
        int month = monthNumberPicker.getValue();
        int day = dayNumberPicker.getValue();
        StringBuilder sb = new StringBuilder();
        sb.append(year).append("-");
        if (month < 10) {
            sb.append("0" + month);
        } else {
            sb.append(month);
        }
        sb.append("-");
        if (day < 10) {
            sb.append("0" + day);
        } else {
            sb.append(day);
        }
        in.putExtra("car_Time_MSG", sb.toString());
        setResult(RESULT_OK, in);
    }

}
